package com.hf.eagle.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ebiz.ssi.web.struts.bean.UploadFile;
import com.hf.eagle.web.base.Keys;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.FileRenamePolicy;

public class CosUploaderServlet extends HttpServlet {
	private static final long serialVersionUID = -3096800116651263134L;

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	private String fileSizeLimit;

	public void init(ServletConfig config) throws ServletException {
		this.fileSizeLimit = config.getInitParameter("fileSizeLimit");
	}

	public void destroy() {
		this.fileSizeLimit = null;
		super.destroy();
	}

	class MyFileRenamePolicy implements FileRenamePolicy {
		public File rename(File file) {
			String fileSaveName = StringUtils.join(new String[] { java.util.UUID.randomUUID().toString(), ".",
					FilenameUtils.getExtension(file.getName()) });
			File result = new File(file.getParentFile(), fileSaveName);
			return result;
		}
	}

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		logger.debug("===========BEGIN CosUploaderServlet DOPOST===========");

		HttpSession session = request.getSession();

		String uploadDir = "files" + File.separatorChar + "upload" + File.separatorChar;
		String autoCreatedDateDirByParttern = "yyyy" + File.separatorChar + "MM" + File.separatorChar + "dd"
				+ File.separatorChar;
		String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(), autoCreatedDateDirByParttern);
		String ctxDir = session.getServletContext().getRealPath(String.valueOf(File.separatorChar));
		if (!ctxDir.endsWith(String.valueOf(File.separatorChar))) {
			ctxDir = ctxDir + File.separatorChar;
		}
		File savePath = new File(ctxDir + uploadDir + autoCreatedDateDir);
		if (!savePath.exists()) {
			savePath.mkdirs();
		}

		String saveDirectory = ctxDir + uploadDir + autoCreatedDateDir;

		if (StringUtils.isBlank(this.fileSizeLimit.toString())) {
			this.fileSizeLimit = "100";// 默认100M
		}
		int maxPostSize = Integer.valueOf(this.fileSizeLimit).intValue() * 1024 * 1024;

		String encoding = "UTF-8";
		FileRenamePolicy rename = new MyFileRenamePolicy();
		MultipartRequest multi = null;
		try {
			multi = new MultipartRequest(request, saveDirectory, maxPostSize, encoding, rename);
		} catch (IOException e) {
			logger.debug(e.getMessage());
			return;
		}

		List<UploadFile> uploadFileList = new ArrayList<UploadFile>();
		UploadFile uploadFile = null;
		Enumeration files = multi.getFileNames();
		while (files.hasMoreElements()) {
			String name = (String) files.nextElement();
			File f = multi.getFile(name);
			if (f != null) {
				String fileName = multi.getFilesystemName(name);
				String lastFileName = saveDirectory + "\\" + fileName;
				String fileSavePath = uploadDir + autoCreatedDateDir + fileName;
				// logger.debug("CosUploaderServlet");
				// logger.debug("文件地址:" + lastFileName);
				// logger.debug("保存路径:" + fileSavePath);
				logger.debug("File Path:{}", lastFileName);
				logger.debug("Save Path:{}", fileSavePath);
				uploadFile = new UploadFile();
				uploadFile.setContentType(multi.getContentType(name));
				uploadFile.setFileName(fileName);
				uploadFile.setFileSavePath(StringUtils.replace(fileSavePath, String.valueOf(File.separatorChar), "/"));
				uploadFileList.add(uploadFile);

			}
		}

		this.setCosUploaderListToSession(session, request, uploadFileList);

		logger.debug("=============END CosUploaderServlet DOPOST============");
	}

	private void setCosUploaderListToSession(HttpSession session, HttpServletRequest request,
			List<UploadFile> uploadFileList) {
		// session有效时间：1个小时
		// session.setMaxInactiveInterval(1 * 60 * 60);
		// session.setAttribute(Keys.COS_UPLOADER_LIST, uploadFileList);

		// 修改 chrome和firefox无法取得 session中的list，所以放到application中
		session.getServletContext().setAttribute(Keys.COS_UPLOADER_LIST, uploadFileList);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public String getFileSizeLimit() {
		return fileSizeLimit;
	}

	public void setFileSizeLimit(String fileSizeLimit) {
		this.fileSizeLimit = fileSizeLimit;
	}

}
